// 路由权限控制
import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import pinia from "@/stores/store" //这里要重新导入才行
import { useUserStore } from './stores/user'
import { useRouterStore } from './stores/router'
import { getUserInfo } from '@/api/auth'
import { constantRoutes } from '@/router'


const whiteList = ['/login']

NProgress.configure({ showSpinner: false })
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // 判断是否已经登录
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    }
    // 这里判断用户信息是否获取
    await checkUserInfo()
    // 然后判断权限和路由信息是否获取
    // 最后根据权限生成动态路由
    next()
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// pinia存储路由数据
const routerStore = useRouterStore(pinia); //这里传参是createPinia()对象
routerStore.$state = { 'list': constantRoutes };


// 验证和请求用户信息
const user = useUserStore(pinia); //这里传参是createPinia()对象
const checkUserInfo = async () => {
  if (!user.id) {
    const ret = await getUserInfo();
    if (ret) {
      user.$patch({
        id: ret.data.id,
        name: ret.data.name,
        avatar: ret.data.avatar,
      })
    }
  }
}

